package com.yin.spring5.dao;

import com.yin.spring5.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * BookDaoImpl
 *
 * @author Yin Guiqing
 */
@Repository
public class BookDaoImpl implements BookDao {
    JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int insert(Book book) {
        String sql = "INSERT INTO book(title,author,price) VALUES(?,?,?)";
        return jdbcTemplate.update(sql, book.getTitle(), book.getAuthor(),
                book.getPrice());
    }

    @Override
    public int update(Book book) {
        String sql = "UPDATE book SET title=?, author=?, price=? WHERE id=?";
        return jdbcTemplate.update(sql, book.getTitle(), book.getAuthor(),
                book.getPrice(), book.getId());
    }

    @Override
    public int delete(Integer id) {
        String sql = "DELETE FROM book WHERE id=?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int recordCount() {
        String sql = "SELECT COUNT(*) FROM book";
        return jdbcTemplate.queryForObject(sql, Integer.TYPE);
    }

    @Override
    public Book getOneById(Integer id) {
        String sql = "SELECT id, title, author, price FROM book WHERE id=?";
        return jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(Book.class), id);
    }

    @Override
    public List<Book> getAll() {
        String sql = "SELECT * FROM book";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
    }

    @Override
    public int[] batchInsert(List<Object[]> bookList) {
        String sql = "INSERT INTO book(title,author,price) VALUES(?,?,?)";
        return jdbcTemplate.batchUpdate(sql, bookList);
    }

    @Override
    public int[] batchUpdate(List<Object[]> bookList) {
        String sql = "UPDATE book SET title=?, author=?, price=? WHERE id=?";
        return jdbcTemplate.batchUpdate(sql, bookList);
    }

    @Override
    public int[] batchDelete(List<Object[]> idList) {
        String sql = "DELETE FROM book WHERE id=?";
        return jdbcTemplate.batchUpdate(sql, idList);
    }
}
